package auth

import (
	"fmt"
	base "gxcvu-ai/app/controller/Base"
	"gxcvu-ai/pkg/config"
	"gxcvu-ai/pkg/helper"
	"gxcvu-ai/pkg/jwt"
	"gxcvu-ai/pkg/response"
	"gxcvu-ai/pkg/verifycode"
	"gxcvu-ai/validate"
	"net/http"

	"gxcvu-ai/app/model/user"

	"github.com/gin-gonic/gin"
)

type AuthController struct {
	base.BaseController
}

// 用戶登錄
func (lc *AuthController) Login(c *gin.Context) {
	request := validate.LoginForm{}

	if ok := validate.Validate(c, &request, validate.ValidateLogin); !ok {
		return
	}

	user, err := user.UserLogin(request.Username, request.Password)
	if err != nil {
		c.AbortWithStatusJSON(http.StatusUnprocessableEntity, gin.H{
			"error": err.Error(),
		})
		return
	}

	token := jwt.NewJWT().IssueToken(user.GetStringID(), user.Name)
	response.CreatedJSON(c, gin.H{
		"token": token,
		"data":  user,
	})
}

// 邮箱是否存在
func (lc *AuthController) SingupEmailExist(c *gin.Context) {
	request := validate.SingupEmailExistForm{}

	if ok := validate.Validate(c, &request, validate.ValidateEmailExist); !ok {
		return
	}

	response.CreatedJSON(c, gin.H{
		"exist": user.IsEmailExit(request.Email),
	})
}

// 发送邮箱验证码
func (lc *AuthController) SingupEmailVerify(c *gin.Context) {
	request := validate.SingupEmailExistForm{}
	if ok := validate.Validate(c, &request, validate.ValidateEmailExist); !ok {
		return
	}
	err := verifycode.NewVerifyCode().SendEmail(request.Email)
	if err != nil {
		response.Abort500(c, "验证码发送失败")
	} else {
		response.Success(c)
	}
}

func (lc *AuthController) Register(c *gin.Context) {
	request := validate.RegisterForm{}

	if ok := validate.Validate(c, &request, validate.ValidateRegitser); !ok {
		return
	}

	user := user.User{
		Email:    request.Email,
		Password: request.Password,
		Name:     fmt.Sprintf("GXCVU%v", helper.RandomNumber(6)),
		Token:    config.GetInt64("chat.register_token"), // 赠送默认TOKEN
	}

	user.Create()

	if user.ID > 0 {
		response.CreatedJSON(c, gin.H{
			"data": user,
		})
	} else {
		response.Abort500(c, "注册失败，请稍后尝试~")
	}

}

// 刷新令牌
func (lc *AuthController) RefreshToken(c *gin.Context) {
	token, err := jwt.NewJWT().RefreshToken(c)
	if err != nil {
		response.Error(c, err, "令牌刷新失败")
	} else {
		response.JSON(c, gin.H{
			"token": token,
		})
	}
}
